package com.geek.factory.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.geek.factory.constant.RedisConstant;
import com.geek.factory.mapper.RoleMenuMapper;
import com.geek.factory.entity.RoleMenu;
import com.geek.factory.service.RoleMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-06-24
 */
@Slf4j
@CacheConfig(cacheNames = RedisConstant.ROLE_MENU_KEY)
@Service
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements RoleMenuService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    @CacheEvict(value = {RedisConstant.MENU_KEY, RedisConstant.ROLE_MENU_KEY}, allEntries = true)
    public boolean save(RoleMenu entity) {
        // 1. 先删除缓存
        redisTemplate.delete(RedisConstant.MENU_KEY + "::*");
        redisTemplate.delete(RedisConstant.ROLE_MENU_KEY + "::*");

        // 2. 保存数据
        boolean result = super.save(entity);

        // 3. 延迟双删策略，再次删除缓存
        try {
            TimeUnit.MILLISECONDS.sleep(300);
            redisTemplate.delete(RedisConstant.MENU_KEY + "::*");
            redisTemplate.delete(RedisConstant.ROLE_MENU_KEY + "::*");
        } catch (InterruptedException e) {
            log.error("延迟双删失败", e);
            Thread.currentThread().interrupt();
        }

        return result;
    }

    @Override
    @CacheEvict(value = {RedisConstant.MENU_KEY, RedisConstant.ROLE_MENU_KEY}, allEntries = true)
    public boolean removeById(RoleMenu entity) {
        // 1. 先删除缓存
        redisTemplate.delete(RedisConstant.MENU_KEY + "::*");
        redisTemplate.delete(RedisConstant.ROLE_MENU_KEY + "::*");

        // 2. 删除数据
        boolean result = super.removeById(entity);

        // 3. 延迟双删策略，再次删除缓存
        try {
            TimeUnit.MILLISECONDS.sleep(300);
            redisTemplate.delete(RedisConstant.MENU_KEY + "::*");
            redisTemplate.delete(RedisConstant.ROLE_MENU_KEY + "::*");
        } catch (InterruptedException e) {
            log.error("延迟双删失败", e);
            Thread.currentThread().interrupt();
        }

        return result;
    }
}
